const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs-extra');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const fileService = require('../services/file.service');
const validationService = require('../services/validation.service');

// 存储配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../uploads'));
  },
  filename: (req, file, cb) => {
    const uniqueName = `${uuidv4()}-${file.originalname}`;
    cb(null, uniqueName);
  }
});

// 文件过滤
const fileFilter = (req, file, cb) => {
  const allowedTypes = ['text/csv', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/plain'];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传CSV、XLSX和TXT文件'), false);
  }
};

// 直接上传的Multer配置
const upload = multer({ 
  storage, 
  fileFilter,
  limits: { fileSize: 50 * 1024 * 1024 } // 50MB限制
});

// 直接上传文件
router.post('/direct', upload.single('file'), async (req, res, next) => {
  try {
    if (!req.file) {
      return res.status(400).json({ success: false, message: '未上传文件' });
    }

    // 获取最大并发量
    const maxConcurrency = parseInt(process.env.MAX_CONCURRENCY);
    
    // 解析文件中的手机号码
    const phoneNumbers = await fileService.parseFile(req.file.path);
    
    if (!phoneNumbers || phoneNumbers.length === 0) {
      // 删除上传的文件
      await fs.unlink(req.file.path);
      return res.status(400).json({ success: false, message: '未从文件中解析到任何手机号码' });
    }

    // 生成唯一ID
    const uploadId = uuidv4();
    
    // 开始验证手机号码
    validationService.startValidation(phoneNumbers, uploadId, maxConcurrency)
      .catch(err => console.error(`验证过程出错: ${err.message}`));

    // 返回上传ID，客户端可以用它查询状态
    res.json({
      success: true,
      uploadId,
      message: '文件上传成功，正在验证手机号码',
      phoneCount: phoneNumbers.length
    });
  } catch (error) {
    next(error);
  }
});

// 初始化分片上传
router.post('/chunk/init', async (req, res, next) => {
  try {
    const { filename, totalSize, totalChunks } = req.body;
    
    if (!filename || !totalSize || !totalChunks) {
      return res.status(400).json({ success: false, message: '缺少必要的参数' });
    }
    
    // 生成上传ID
    const uploadId = uuidv4();
    
    // 创建分片上传目录
    const chunkDir = path.join(__dirname, '../temp', uploadId);
    await fs.ensureDir(chunkDir);
    
    res.json({
      success: true,
      uploadId,
      message: '分片上传初始化成功'
    });
  } catch (error) {
    next(error);
  }
});

// 上传分片
router.post('/chunk/upload', multer({ 
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      const chunkDir = path.join(__dirname, '../temp', req.body.uploadId);
      cb(null, chunkDir);
    },
    filename: (req, file, cb) => {
      // 用分片索引作为文件名
      cb(null, `${req.body.chunkIndex}`);
    }
  }),
  limits: { fileSize: 10 * 1024 * 1024 } // 每个分片最大10MB
}).single('chunk'), async (req, res, next) => {
  try {
    const { uploadId, chunkIndex } = req.body;
    
    if (!uploadId || !chunkIndex) {
      return res.status(400).json({ success: false, message: '缺少必要的参数' });
    }
    
    const chunkDir = path.join(__dirname, '../temp', uploadId);
    if (!await fs.pathExists(chunkDir)) {
      return res.status(404).json({ success: false, message: '上传ID不存在' });
    }
    
    res.json({
      success: true,
      message: `分片 ${chunkIndex} 上传成功`
    });
  } catch (error) {
    next(error);
  }
});

// 完成分片上传
router.post('/chunk/complete', async (req, res, next) => {
  try {
    const { uploadId, filename, totalChunks } = req.body;
    
    if (!uploadId || !filename || !totalChunks) {
      return res.status(400).json({ success: false, message: '缺少必要的参数' });
    }
    
    const chunkDir = path.join(__dirname, '../temp', uploadId);
    if (!await fs.pathExists(chunkDir)) {
      return res.status(404).json({ success: false, message: '上传ID不存在' });
    }
    
    // 合并分片
    const destPath = path.join(__dirname, '../uploads', `${uploadId}-${filename}`);
    await fileService.mergeChunks(chunkDir, destPath, totalChunks);
    
    // 解析文件中的手机号码
    const phoneNumbers = await fileService.parseFile(destPath);
    
    if (!phoneNumbers || phoneNumbers.length === 0) {
      // 删除上传的文件和临时目录
      await fs.unlink(destPath);
      await fs.remove(chunkDir);
      return res.status(400).json({ success: false, message: '未从文件中解析到任何手机号码' });
    }
    
    // 开始验证手机号码
    validationService.startValidation(
      phoneNumbers, 
      uploadId, 
      parseInt(process.env.MAX_CONCURRENCY)
    ).catch(err => console.error(`验证过程出错: ${err.message}`));
    
    // 删除临时分片目录
    await fs.remove(chunkDir);
    
    res.json({
      success: true,
      uploadId,
      message: '文件上传完成，正在验证手机号码',
      phoneCount: phoneNumbers.length
    });
  } catch (error) {
    next(error);
  }
});

// 查询上传状态
router.get('/status/:uploadId', async (req, res, next) => {
  try {
    const { uploadId } = req.params;
    const status = await validationService.getValidationStatus(uploadId);
    
    if (!status) {
      return res.status(404).json({ success: false, message: '上传ID不存在' });
    }
    
    res.json({
      success: true,
      status: status.status,
      progress: status.progress,
      resultUrls: status.resultUrls ? {
        valid: status.resultUrls.valid ? `${process.env.DOWNLOAD_URI}/api/results/${path.basename(status.resultUrls.valid)}` : null,
        invalid: status.resultUrls.invalid ? `${process.env.DOWNLOAD_URI}/api/results/${path.basename(status.resultUrls.invalid)}` : null,
        failed: status.resultUrls.failed ? `${process.env.DOWNLOAD_URI}/api/results/${path.basename(status.resultUrls.failed)}` : null,
      } : null,
      message: status.message
    });
  } catch (error) {
    next(error);
  }
});

module.exports = router;
